//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {

    /**
     * 加载进度界面
     * loading process interface
     */
    private loadingView:LoadingUI;
    private frameItem:FrameItem;
    protected createChildren(): void {
        super.createChildren();
        this.name = "main";
        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin

            context.onUpdate = () => {

            }
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }
        //egret.log("Main:initializing..");
        // AnchorUtil.init();

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
        //egret.log("Main:Added to stage",this.stage.stageWidth,":",this.stage.stageHeight);
        game.QZoneConfig.init();//不在游戏里面调用就不会被包含进去
        GameConst.Api_Url = (window["apiUrl"] || "")+"/";
        GameConst.Version = window["version"] || "";
        GameConst.Res_Root = window["resBase"] || "";
        GameConst.Res_Server = window["resServer"] || "";
        GameConst.StageH = this.stage.stageHeight;
        GameConst.StageW = this.stage.stageWidth;
        
        //Config loading process interface
        //设置加载进度界面
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);
        // initialize the Resource loading library
        this.frameItem = new FrameItem();
        this.frameItem.callObj = this;
        this.frameItem.callFun = this.checkPetList;
        FrameMgr.getInstance().initStage(this.stage);
        GameConst.Stage = this.stage;
        //初始化Resource资源加载库
        // RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        // RES.loadConfig("resource/resource.json?v="+GameConst.Version,"resource/");

        //egret.log("Main:loading resource.json");
    }
	
    private async runGame() {
        await this.loadResource()
        this.createGameScene();
	    //todo
        // const result = await RES.getResAsync("description_json")
        // this.startAnimation(result);
        // await platform.login();
        // const userInfo = await platform.getUserInfo();
        // console.log(userInfo);

    }
    
    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await RES.loadConfig("resource/default.res.json?v="+GameConst.Version, "resource/");
		    await this.loadTheme();
            await RES.loadGroup("preload", 0, loadingView);
            this.onConfigComplete();
            // await RES.loadGroup("common",0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }
    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }
    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * Loading of configuration file is complete, start to pre-load the preload resource group
     */
    private onConfigComplete():void {
        //egret.log("Main:resource load complete",this.stage.stageWidth,this.stage.stageHeight);
        this.createGameScene();
        // RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.loadGroup("common");
    }

    private checkPetList(delate:number){
        if( Model.pets !== undefined){
            FrameMgr.getInstance().delController(this.name);
            this.doLoad();
        }
    }

    private doLoad(){
        if(Model.pets.length > 0){
            //egret.log("Main:load preload");
            RES.loadGroup("preload");
        }else{
            //egret.log("Main:load create");
            RES.loadGroup("create");
        }
    }
    /**
     * preload资源组加载完成
     * preload resource group is loaded
     */
    private onResourceLoadComplete(event:RES.ResourceEvent):void {
        //egret.log("Main:group loaded == >",event.groupName);
        if( event.groupName == "common"){
            if( Model.pets !== undefined){
                this.doLoad();
            }else {
                FrameMgr.getInstance().addControll(this.frameItem);
            }
        }else if(event.groupName == "create"){
            //egret.log("Main:add CreateRoleScene");
            DisplayController.instance().addUiElement(CreateRoleScene.getInstance());
            RES.loadGroup("preload");
            // GuideController.getInstance().start();
            this.parent.removeChild(this);
        }else if (event.groupName == "preload") {
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            EffectMgr.getInstance().initConfig(RES.getRes("effects_json"));

            if(Model.pets.length != 0 && MainScene.getInstance().parent == undefined){
                //egret.log("Main:add MainScene");
                PetMgr.getInstance().start();
                DisplayController.instance().addUiElement(DiamondElement.getInstance());
                DiamondElement.getInstance().updateDisplay();
                //DisplayController.instance().addUiElement(MainScene.getInstance());
                DisplayController.instance().addUiElement(MainTab.getInstance());
                SceneMgr.getInstance().switchScene(SceneMgr.SCENE_MAIN);


                if( Model.me.step < Model.MaxGuideStep){
                    GuideController.getInstance().start();
                }
                //window["__auto"]();
            }
            if( this.loadingView != null && this.loadingView.parent != null)
                this.loadingView.parent.removeChild(this.loadingView);
            if( this.parent)
                this.parent.removeChild(this);
    
            var grayMask:eui.Image = new eui.Image(RES.getRes("preload_json.graymask"));
            grayMask.width = GameConst.StageW;
            grayMask.height = GameConst.StageH;
            grayMask.touchEnabled = true;
            grayMask.name = "mask";
            GameConst.GrayMask = grayMask;
            this.checkAnouncement();
            //RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.loadGroup("sounds",-1);
        }else if(event.groupName == "sounds"){
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            SoundMgr.getInstance().isSoundLoaded = true;
            //game.SoundMgr.getInstance().playBg();
        }
    }

    public checkAnouncement(){
        var date = RES.getRes("anouncement_json").date;
        var saveDate = egret.localStorage.getItem(Model.me.id+"anouncementdate");
        if( date != saveDate &&  Model.me.step >= 9){
            AnouncementPanel.getInstance().show();
            egret.localStorage.setItem(Model.me.id+"anouncementdate",date);
        }
    }

    /**
     * 资源组加载出错
     * Resource group loading failed
     */
    private onResourceLoadError(event:RES.ResourceEvent):void {
        egret.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //ignore loading failed projects
        this.onResourceLoadComplete(event);
    }

    /**
     * preload资源组加载进度
     * loading process of preload resource
     */
    private onResourceProgress(event:RES.ResourceEvent):void {
        if (event.groupName == "preload") {
            this.loadingView.onProgress(event.itemsLoaded, event.itemsTotal);
        }
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    private createGameScene():void {
        var bg:egret.Bitmap = new egret.Bitmap();
        this.stage.addChild(bg);
        DisplayController.instance().bg = bg;
        var gameLayer = new egret.DisplayObjectContainer();
        this.stage.addChild(gameLayer);
        //GUI的组件必须都在这个容器内部,UIStage会始终自动保持跟舞台一样大小。
        //GUI components must be within the container, UIStage will always remain the same as stage size automatically.
        var uiLayer = new egret.DisplayObjectContainer();
        this.stage.addChild(uiLayer);
        DisplayController.instance().setContainer(this.stage,gameLayer, uiLayer);
        //egret.Profiler.getInstance().run();
    }
}


